<?php
/**
 * Created by PhpStorm.
 * User: 牛赞赞
 * Date: 2021/2/3
 * Time: 14:07
 */

namespace App\Game\Logic;


use App\Game\Conf\MainCmd;
use App\Game\Conf\SubCmd;
use App\Game\Core\AStrategy;
use App\Game\Core\Packet;

class TakeOverUser extends AStrategy
{
    public function exec()
    {
        $account = $this->_params['userinfo']['account'];
        $fd = $this->_params['userinfo']['fd'];
//        $room_no = isset($this->_params['data']['room_no']) ? $this->_params['data']['room_no'] : null;
        $take_over = isset($this->_params['data']['take_over']) ? $this->_params['data']['take_over'] : null;
        $serv = $this->_params['serv'];
//        $fds       = $this->getFdsByRoomNo($room_no);
        $game_conf = $this->game_conf;
        $user_conf = $this->user_conf;

        $room_no = $this->getRoomNo($account);
        if (!$room_no) {
            $msg = ['status' => 1, 'info' => '操作失败，房间不存在'];
            pushDataToUser($serv, $fd, $msg, SubCmd::SUB_GAME_TAKE_OVER);
            pushForceQuitMsg($room_no,$account);
        } elseif ($take_over === null) {
            $msg = ['status' => 2, 'info' => '托管参数缺失'];
            pushDataToUser($serv, $fd, $msg, SubCmd::SUB_GAME_TAKE_OVER);
        } else {
            // 加锁
            $data_lock_key = sprintf($user_conf['user_room_data_lock'], $room_no);
            $room_data_key = sprintf($game_conf['user_room_data'], $room_no);
            do {
                $result = redis()->set($data_lock_key, $room_no, ['nx', 'ex' => 1]);  //nx代表当key不存在时设置 ex代表设置过期时间
                if ($result) {
                    // 设置玩家托管状态
                    if (redis()->exists($room_data_key)) {
                        $user_data = json_decode(redis()->hGet($room_data_key, (string)$account), true);
                        $user_data['take_over'] = $take_over;
                        redis()->hSet($room_data_key, (string)$account, json_encode($user_data));
                    }
                    redis()->del($data_lock_key);
                    continue;
                }
            } while (!$result);

            $chair_id = $this->findChairId($room_no, $account);
            $msg = ['chair_id' => $chair_id, 'take_over' => $take_over];
//            $data = Packet::packFormat('OK', 1, $msg);
//            $data = Packet::packEncode($data, MainCmd::CMD_SYS, SubCmd::SUB_GAME_TAKE_OVER);
//            $this->pushToUsers($serv, $fds, $data);
            broadCast($room_no, $msg, SubCmd::SUB_GAME_TAKE_OVER);
        }
    }

}